﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
/*********************************
 * 标题：加密助手类
 * 描述：含习网式加密（SHA2不可破），微软内置DES加密
 * 开发：单车上的程序猿（2014.10.24）
 * 编辑：      
 * 备注：  
 * ******************************/

namespace QiBu.Api.Helper.Com
{
    /// <summary>
    /// 加密助手类
    /// </summary>
    public static class MD5AndXOREncrypt
    {
        private const string key = "9$</Zu!j";   //对称密钥

        #region 微软内置加解密

        /// <summary>
        /// C#内置DES加密
        /// </summary>
        /// <param name="pToEncrypt">要加密的字符串（非中文）</param>
        /// <returns>结果</returns>
        public static string DesEncrypt(string pToEncrypt, string ekey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            des.Key = ASCIIEncoding.ASCII.GetBytes(ekey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(ekey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }

        /// <summary>
        /// C#内置DES解密
        /// </summary>
        /// <param name="pToDecrypt">要解密的字符串</param>
        /// <returns>结果</returns>
        public static string DesDecrypt(string pToDecrypt, string dkey)
        {
            if (string.IsNullOrEmpty(pToDecrypt))
            {
                return "0";
            }
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(dkey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(dkey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
        #endregion

        #region 习网式加密

        /// <summary>
        /// 非对称加密
        /// </summary>
        /// <param name="instr"></param>
        /// <returns></returns>
        public static string Encrypt(string instr)
        {
            return SaltAndHash(instr, key);
        }

        /// <summary>
        /// SHA-512/SHA2
        /// </summary>
        /// <param name="rawString"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        private static string SaltAndHash(this string rawString, string salt)
        {
            return (rawString + salt).SHA512();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private static string SHA512(this string text)
        {
            return text.EncryptOneWay<SHA512Cng, UTF8Encoding>();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="Algorithm"></typeparam>
        /// <typeparam name="StringEncoding"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string EncryptOneWay<Algorithm, StringEncoding>(this string str)
            where Algorithm : HashAlgorithm
            where StringEncoding : Encoding
        {
            byte[] bytes = Activator.CreateInstance<StringEncoding>().GetBytes(str);
            return BitConverter.ToString(Activator.CreateInstance<Algorithm>().ComputeHash(bytes)).Replace("-", "");
        }

        #endregion
    }
}
